package com.itheima.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component //定时任务 读取redis的缓存数据 加载到 mongo中
public class RecommendMovementJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;
    //应该是每一个小时拉取一次
    //@Scheduled(cron = "* * 0/1 * * *")  //TODO 以后生产环境自己改造
    @Scheduled(cron = "0/5 * * * * *") //测试使用
    public void run(){
        System.out.println("定时拉取缓存数据");
        //1. 拉取缓存数据  全部拉取 获得一组全部的key
        Set<String> keys = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");
        //2.根据key 获得指定的数据
        if(CollectionUtil.isNotEmpty(keys)){
            for (String key : keys) {
                //3.获得每一个缓存值  pids=27,10015,26,28,19,10040,10064,25,100099,100092,100093,24
                String value = stringRedisTemplate.opsForValue().get(key);

                String userId = key.replaceAll("MOVEMENTS_RECOMMEND_" , "");
                //4.截取动态值
                String[] pids = value.split(",");
                //5.开始遍历这个数组
                for (String pid : pids) {
                    //构建数据
                    RecommendMovement recommendMovement = new RecommendMovement();

                    recommendMovement.setCreated(System.currentTimeMillis());
                    recommendMovement.setUserId( Long.valueOf(userId) );//用户id
                    recommendMovement.setPid(Long.valueOf(pid));//pid
                    //根据pid查询动态id
                    Query query = new Query(Criteria.where("pid").is(Long.valueOf(pid)));
                    Movement movement = mongoTemplate.findOne(query, Movement.class);
                    recommendMovement.setPublishId(movement.getId());//动态id
                    recommendMovement.setScore(RandomUtil.randomDouble(60,90));//得分  大数据平台有点小bug 没有推送分数  跟大数据沟通 将分数也推送回来

                    //目的: 往推荐动态表中保存 数据
                    mongoTemplate.save(recommendMovement);
                }
            }
        }
    }
}
